<template>
    <div>
        <div>
            <div class="affix_box">
                <el-affix :offset="20">
                    <div class="selector">
                        <el-select v-model="well_value" placeholder="请选择井别" style="width: 240px" filterable
                            @change="getWellInfo(well_value)">
                            <el-option v-for="item in options" :key="item.value" :value="item.value" />
                        </el-select>
                        <div>
                            <el-button type="primary" plain @click="showStopData"
                                v-show="isShowToggle1">展示停喷井组</el-button>
                            <el-button type="primary" plain @click="addtoStopData(well_value)"
                                v-show="isShowToggle1">将{{
                                well_value }}添加到停喷井组</el-button>

                            <el-button type="primary" plain @click="showNostopData"
                                v-show="!isShowToggle1">展示非停喷井组</el-button>
                            <el-button type="primary" plain @click="addtoNostopData(well_value)"
                                v-show="!isShowToggle1">将{{
                                well_value }}添加到非停喷井组</el-button>
                            <el-button type="primary" plain @click="showStopPreRes(well_value)">
                                展示高风险区间
                            </el-button>

                        </div>

                    </div>
                    <!-- <p class="select_title">积液时间选择(点击图中生产时间自动填写时间点):</p> -->

                </el-affix>
            </div>
            <!-- <el-table :data="secondDataDict" style="width: 100%" max-height="250">
                <el-table-column fixed prop="date" label="Date" width="150" />
            </el-table> -->
            <div class="charts" ref="container" v-loading="loading">
                <highcharts class="hc" :options="chartOptions1" ref="chartRef1" :constructorType="'stockChart'">
                </highcharts>
                <highcharts class="hc" :options="chartOptions2" ref="chartRef2" :constructorType="'stockChart'">
                </highcharts>
                <highcharts class="hc" :options="chartOptions3" ref="chartRef3" :constructorType="'stockChart'">
                </highcharts>
                <highcharts class="hc" :options="chartOptions4" ref="chartRef4" v-show="true"
                    :constructorType="'stockChart'">
                </highcharts>

                <!-- <highcharts class="hc" :options="chartOptions2" ref="chart" v-if="flag" :constructorType="'stockChart'"></highcharts> -->
            </div>
        </div>


    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { wellFindById, denoseData, saveLabels, getGoodWellPreview, getBadWellPreview, addWellToGood, addWellToBad, getWaterOrNormalPreview, addToWaterOrNormal, saveUsefulTimeInterval, addToNorm, getAbNormalPreview, addToStopOrNostop, showStopOrNostop } from '@/config/api'
import { cloneDeep } from 'lodash';
import { ElMessage, ElMessageBox } from 'element-plus'
import { anomaly_res_data, predict_data, predict_stop_data, save_predict_label } from "@/pyconfig/api"
import { addToValid, getGoodOrBadOrValidPreview, } from "@/config/api"
import { findConsecutiveOnes } from '@/config/util';
import { fi } from 'element-plus/es/locales.mjs';

const loading = ref(false)



const well_value = ref("七里025-X1_石炭系")
const time_value = ref()
const water_time_value1 = ref()
const water_time_value2 = ref()
const time_start_flag = ref(false);
const time_end_flag = ref(false);
const disabled = ref(true);

const options = ref()
const show_save_button_click = ref(false)

// =====================停喷风险检测=============================
const  showStopPreRes = async (_uid: number | string) => {

    console.log(`output->1`, new Date())
    const { data } = await predict_stop_data(_uid)
    // const { data } = await predict_data(_uid)
    ElMessageBox.alert("预测成功", {
        confirmButtonText: 'OK',
    })
    console.log(`predict_stop_data->`,data)                                                                            
    const final_data = process_data(data.data.data)
    data_dict.value["well_id"] = final_data["井号"] && final_data["井号"][0] ? final_data["井号"][0] : null;
    data_dict.value["cengwei_id"] = final_data["层位"] && final_data["层位"][0] ? final_data["层位"][0] : null;
    data_dict.value["date"] = final_data["生产日期"] ? final_data["生产日期"] : [];
    data_dict.value["time"] = final_data["生产时间"] ? final_data["生产时间"] : [];
    data_dict.value["gasPerDay"] = final_data["日产气"] ? final_data["日产气"] : [];
    data_dict.value["waterPerDay"] = final_data["日产水"] ? final_data["日产水"] : [];
    data_dict.value["avgOilPressure"] = final_data["平均油压"] ? final_data["平均油压"] : [];
    data_dict.value["avgCasingPressure"] = final_data["平均套压"] ? final_data["平均套压"] : [];
    data_dict.value["diffOC"] = final_data["套油压差"] ? final_data["套油压差"] : [];
    data_dict.value["ratioWG"] = final_data["水气比"] ? final_data["水气比"] : [];
    data_dict.value["gasVaryRate"] = final_data["油压变化速率"] ? final_data["油压变化速率"] : [];
    data_dict.value["diffVaryRate"] = final_data["套油压差_slope"] ? final_data["套油压差_slope"] : [];
    data_dict.value["label"] = final_data["label"] ? final_data["label"] : [];
    data_dict.value["usefulLabel"] = final_data["可用时间段"] ? final_data["可用时间段"] : [];
    data_dict.value["pre_label"] = final_data["pre_label"] ? final_data["pre_label"] : [];
    data_dict.value["stop_label"] = final_data["stop_label"] ? final_data["stop_label"] : [];
    data_dict.value["gas_VaryRate"] = final_data["日产气_slope"] ? final_data["日产气_slope"] : [];
    newDataDict.value = cloneDeep(data_dict.value);
    water_time_value1.value = formatDate(new Date(data_dict.value["date"][0]))
    water_time_value2.value = formatDate(new Date(data_dict.value["date"][data_dict.value["date"].length - 1]))
    show_save_button_click.value = true
    const [result1, result2] = findConsecutiveOnes(data_dict.value["stop_label"]);
    removePlotBand([chartRef1, chartRef2])
    if (result1.length > 0) {
        addDangerPlotBand([chartRef1, chartRef2], result1)
    }
}

// =====================预测=============================
const getPredRes = async (_uid: number | string) => {
    loading.value = true
    console.log(`output->1`, new Date())
    const { data } = await predict_data(_uid)
    // const { data } = await predict_data(_uid)

    ElMessageBox.alert("预测成功", {
        confirmButtonText: 'OK',
    })
    loading.value = false
    console.log(`output->2`, new Date())
    console.log(`pre->data`, data)
    const final_data = process_data(data.data.data)
    data_dict.value["well_id"] = final_data["井号"] && final_data["井号"][0] ? final_data["井号"][0] : null;
    data_dict.value["cengwei_id"] = final_data["层位"] && final_data["层位"][0] ? final_data["层位"][0] : null;
    data_dict.value["date"] = final_data["生产日期"] ? final_data["生产日期"] : [];
    data_dict.value["time"] = final_data["生产时间"] ? final_data["生产时间"] : [];
    data_dict.value["gasPerDay"] = final_data["日产气"] ? final_data["日产气"] : [];
    data_dict.value["waterPerDay"] = final_data["日产水"] ? final_data["日产水"] : [];
    data_dict.value["avgOilPressure"] = final_data["平均油压"] ? final_data["平均油压"] : [];
    data_dict.value["avgCasingPressure"] = final_data["平均套压"] ? final_data["平均套压"] : [];
    data_dict.value["diffOC"] = final_data["套油压差"] ? final_data["套油压差"] : [];
    data_dict.value["ratioWG"] = final_data["水气比"] ? final_data["水气比"] : [];
    data_dict.value["gasVaryRate"] = final_data["油压变化速率"] ? final_data["油压变化速率"] : [];
    data_dict.value["diffVaryRate"] = final_data["套油压差_slope"] ? final_data["套油压差_slope"] : [];
    data_dict.value["label"] = final_data["label"] ? final_data["label"] : [];
    data_dict.value["usefulLabel"] = final_data["可用时间段"] ? final_data["可用时间段"] : [];
    data_dict.value["pre_label"] = final_data["pre_label"] ? final_data["pre_label"] : [];
    data_dict.value["gas_VaryRate"] = final_data["日产气_slope"] ? final_data["日产气_slope"] : [];
    newDataDict.value = cloneDeep(data_dict.value);
    water_time_value1.value = formatDate(new Date(data_dict.value["date"][0]))
    water_time_value2.value = formatDate(new Date(data_dict.value["date"][data_dict.value["date"].length - 1]))
    show_save_button_click.value = true
    const [result1, result2] = findConsecutiveOnes(data_dict.value["pre_label"]);
    removePlotBand([chartRef1, chartRef2])
    if (result1.length > 0) {
        addWarningPlotBand([chartRef1, chartRef2], result1)
    }
    if (result2.length > 0) {
        addDangerPlotBand([chartRef1, chartRef2], result2)
    }
    // 显示预测时间段
    const index_now = data_dict.value["date"].findIndex((date: string) => date == formatDate(new Date()));
    const index_end = data_dict.value["date"].findIndex((date: string) => date == water_time_value2.value);
    console.log(`output->index_now`, index_now, index_end)
    const arr = [chartRef1, chartRef2]
    if (index_now != -1) {
        arr.forEach((chartref) => {
            chartref.value.chart.xAxis[0].addPlotBand({
                from: index_now,
                to: index_end,
                color: 'RGBA(255, 0, 0, 0.2)',
                label: {
                    text: `
                    预测数据区域
                    <br>
                    `, // 注释文本
                    style: {
                        color: '#000', // 文本颜色
                        fontWeight: 'bold' // 字体粗细
                    },
                    verticalAlign: 'middle',
                    align: 'left',


                }
            })
        })
    }


    // 显示预测时间段


}
// =====================异常检测=============================
const getAnomalyRes = async (_uid: number | string) => {
    try {
        loading.value = true
        console.log(`output->1`, new Date())
        const { data } = await anomaly_res_data(_uid)
        // const { data } = await predict_data(_uid)

        ElMessageBox.alert("检测成功", {
            confirmButtonText: 'OK',
        })
        loading.value = false
        console.log(`output->2`, new Date())
        // console.log(`output->data`,data)
        const final_data = process_data(data.data.data)
        console.log(`output->3`, final_data)
        data_dict.value["well_id"] = final_data["井号"] && final_data["井号"][0] ? final_data["井号"][0] : null;
        data_dict.value["cengwei_id"] = final_data["层位"] && final_data["层位"][0] ? final_data["层位"][0] : null;
        data_dict.value["date"] = final_data["生产日期"] ? final_data["生产日期"] : [];
        data_dict.value["time"] = final_data["生产时间"] ? final_data["生产时间"] : [];
        data_dict.value["gasPerDay"] = final_data["日产气"] ? final_data["日产气"] : [];
        data_dict.value["waterPerDay"] = final_data["日产水"] ? final_data["日产水"] : [];
        data_dict.value["avgOilPressure"] = final_data["平均油压"] ? final_data["平均油压"] : [];
        data_dict.value["avgCasingPressure"] = final_data["平均套压"] ? final_data["平均套压"] : [];
        data_dict.value["diffOC"] = final_data["套油压差"] ? final_data["套油压差"] : [];
        data_dict.value["ratioWG"] = final_data["水气比"] ? final_data["水气比"] : [];
        data_dict.value["gasVaryRate"] = final_data["油压变化速率"] ? final_data["油压变化速率"] : [];
        data_dict.value["diffVaryRate"] = final_data["套油压差_slope"] ? final_data["套油压差_slope"] : [];
        data_dict.value["label"] = final_data["label"] ? final_data["label"] : [];
        data_dict.value["usefulLabel"] = final_data["可用时间段"] ? final_data["可用时间段"] : [];
        data_dict.value["pre_label"] = final_data["anomaly"] ? final_data["anomaly"] : [];
        data_dict.value["gas_VaryRate"] = final_data["日产气_slope"] ? final_data["日产气_slope"] : [];
        newDataDict.value = cloneDeep(data_dict.value);
        water_time_value1.value = formatDate(new Date(data_dict.value["date"][0]))
        water_time_value2.value = formatDate(new Date(data_dict.value["date"][data_dict.value["date"].length - 1]))
        show_save_button_click.value = true
        const [result1, result2] = findConsecutiveOnes(data_dict.value["pre_label"]);
        removePlotBand([chartRef1, chartRef2])
        if (result1.length > 0) {
            addWarningPlotBand([chartRef1, chartRef2], result1)
        }
        if (result2.length > 0) {
            addDangerPlotBand([chartRef1, chartRef2], result2)
        }
        // 显示预测时间段
        const index_now = data_dict.value["date"].findIndex((date: string) => date == formatDate(new Date()));
        const index_end = data_dict.value["date"].findIndex((date: string) => date == water_time_value2.value);
        console.log(`output->index_now`, index_now, index_end)
        const arr = [chartRef1, chartRef2]
        if (index_now != -1) {
            arr.forEach((chartref) => {
                chartref.value.chart.xAxis[0].addPlotBand({
                    from: index_now,
                    to: index_end,
                    color: 'RGBA(255, 0, 0, 0.2)',
                    // label: {
                    //     text: `
                    // 预测数据区域
                    // <br>
                    // `, // 注释文本
                    //     style: {
                    //         color: '#000', // 文本颜色
                    //         fontWeight: 'bold' // 字体粗细
                    //     },
                    //     verticalAlign: 'middle',
                    //     align: 'left',


                    // }
                })
            })
        }


        // 显示预测时间段
    } catch (error) {
        console.error('error is', error)

    }



}

// =====================预测=============================

// ================数据质量切换begin======================
let isShowToggle = ref(true)
let isShowToggle1 = ref(true)
// ================数据质量切换end======================

// ================停喷数据切换begin======================

// 添加到停喷井组
const addtoStopData = async (well_value: string) => {
    
    const index = options.value.findIndex((item: any) => item.value == well_value)
    // console.log(`output->data.data`, options.value.findIndex((item: any) => item.value == well_value))
    const param = `${well_value}_1`
    const { data } = await addToStopOrNostop(param)
    showNostopData(index)
}
const addtoNostopData = async (well_value: string) => {
    
    const index = options.value.findIndex((item: any) => item.value == well_value)
    // console.log(`output->data.data`, options.value.findIndex((item: any) => item.value == well_value))
    const param = `${well_value}_0`
    const { data } = await addToStopOrNostop(param)
    showNostopData(index)
}
// 展示

const showStopData = async (index = 0) => {
    const { data } = await showStopOrNostop("1")
    options.value = data.data
    well_value.value = (index < options.value.length) ? options.value[index]['value'] : options.value[0]['value']
    isShowToggle1.value = false
    getWellInfo(well_value.value)
}
const showNostopData = async (index = 0) => {
    const { data } = await showStopOrNostop("0")
    options.value = data.data
    well_value.value = (index < options.value.length) ? options.value[index]['value'] : options.value[0]['value']
    isShowToggle1.value = true
    getWellInfo(well_value.value)
}





// ================积液数据切换end======================

let flag = ref(false)
const handle_button_click = computed(() => {
    if (time_end_flag.value == true && time_start_flag.value == true) {
        disabled.value = false
    }
    else {
        disabled.value = true
    }
    return disabled.value

})

const data_dict = ref<any>({
    "well_id": "",
    "cengwei_id": "",
    "date": [],
    "time": [],
    "gasPerDay": [],
    "waterPerDay": [],
    "avgOilPressure": [],
    "avgCasingPressure": [],
    "diffOC": [],
    "ratioWG": [],
    "gasVaryRate": [],
    "label": [],
})
const chartRef1 = ref()
const chartRef2 = ref()
const chartRef3 = ref()
const chartRef4 = ref()

onMounted(() => {
    //初始化数据
    showNostopData()
    getWellInfo(well_value.value)
    if (data_dict.value["date"]) {
        flag.value = true
    }
})


// const getWellPreview = async () => {
//     const { data } = await wellPreview()
//     options.value = data.data
//     // console.log(`output->`, options.value)
// }
const newDataDict = ref<any>({
    "well_id": "",
    "cengwei_id": "",
    "date": [],
    "time": [],
    "gasPerDay": [],
    "waterPerDay": [],
    "avgOilPressure": [],
    "avgCasingPressure": [],
    "diffOC": [],
    "ratioWG": [],
    "gasVaryRate": [],
    "diffVaryRate": [],
    "label": [],
    "usefulLabel": [],
})//备份数据



const getWellInfo = async (_uid: number | string) => {
    try {
        const { data } = await wellFindById(_uid)
        // console.log(`output->data`,data)
        const final_data = process_data(data.data)
        console.log(`final_data->`, final_data)
        data_dict.value["well_id"] = final_data["井号"] ? final_data["井号"][0] : null;
        data_dict.value["cengwei_id"] = final_data["层位"] ? final_data["层位"][0] : null;
        data_dict.value["date"] = final_data["生产日期"] ? final_data["生产日期"] : [];
        data_dict.value["time"] = final_data["生产时间"] ? final_data["生产时间"] : [];
        data_dict.value["gasPerDay"] = final_data["日产气"] ? final_data["日产气"] : [];
        data_dict.value["waterPerDay"] = final_data["日产水"] ? final_data["日产水"] : [];
        data_dict.value["avgOilPressure"] = final_data["平均油压"] ? final_data["平均油压"] : [];
        data_dict.value["avgCasingPressure"] = final_data["平均套压"] ? final_data["平均套压"] : [];
        data_dict.value["diffOC"] = final_data["套油压差"] ? final_data["套油压差"] : [];
        data_dict.value["ratioWG"] = final_data["水气比"] ? final_data["水气比"] : [];
        data_dict.value["gasVaryRate"] = final_data["油压变化速率"] ? final_data["油压变化速率"] : [];
        data_dict.value["diffVaryRate"] = final_data["套油压差_slope"] ? final_data["套油压差_slope"] : [];
        data_dict.value["label"] = final_data["label"] ? final_data["label"] : [];
        data_dict.value["usefulLabel"] = final_data["可用时间段"] ? final_data["可用时间段"] : [];
        data_dict.value["pre_label"] = [];
        data_dict.value["gas_VaryRate"] = final_data["日产气_slope"] ? final_data["日产气_slope"] : [];
        newDataDict.value = cloneDeep(data_dict.value);
        const [result1, result2] = findConsecutiveOnes(data_dict.value["label"]);
        removePlotBand([chartRef1, chartRef2],)
        if (result1.length > 0) {
            addWarningPlotBand([chartRef1, chartRef2], result1)
        }
        if (result2.length > 0) {
            addDangerPlotBand([chartRef1, chartRef2], result2)
        }


        water_time_value1.value = formatDate(new Date(data_dict.value["date"][0]))
        water_time_value2.value = formatDate(new Date(data_dict.value["date"][data_dict.value["date"].length - 1]))
    } catch (e) {
        console.log(`error->`, e)
    } finally {
        show_save_button_click.value = false
    }




}

const removePlotBand = (chartreflist: Array<any>) => {
    chartreflist.forEach(chartref => {
        while (chartref.value.chart.xAxis[0].plotLinesAndBands.length > 0) {
            chartref.value.chart.xAxis[0].removePlotBand(chartref.value.chart.xAxis[0].plotLinesAndBands[0].id);
        }
    })
};
const addWarningPlotBand = (chartreflist: Array<any>, warning_arr: Array<any>) => {
    const col = ['#FFEB3B', '#E91E63']
    warning_arr.forEach((interval, i) => {
        chartreflist.forEach((chartref) => {
            chartref.value.chart.xAxis[0].addPlotBand({
                from: interval[0],
                to: interval[1],
                color: '#FFEB3B',
                id: `plot-band1-${i}`,
                // label: {
                //     text: `
                //     起止时间:
                //     <br>
                //     ${data_dict.value["date"][interval[0]]} 
                //     <br>
                //     ${data_dict.value["date"][interval[1]]}

                //     <br>

                //     停喷风险：低
                //     `, // 注释文本
                //     style: {
                //         color: '#000', // 文本颜色
                //         fontWeight: 'bold' // 字体粗细
                //     },
                //     verticalAlign:'top'
                // }
            });
        });
    });
};
const addDangerPlotBand = (chartreflist: Array<any>, danger_arr: Array<any>) => {
    const col = ['#FFEB3B', '#E91E63']
    danger_arr.forEach((interval, i) => {
        chartreflist.forEach((chartref) => {
            chartref.value.chart.xAxis[0].addPlotBand({
                from: interval[0],
                to: interval[1],
                color: '#E91E63',
                id: `plot-band2-${i}`,
                // label: {
                //     text: `
                //     起止时间:
                //     <br>
                //     ${data_dict.value["date"][interval[0]]} 
                //     <br>
                //     ${data_dict.value["date"][interval[1]]}
                //     </br>
                //     <br>
                //     停喷风险：高
                //     <br>

                //     <br>

                //     `, // 注释文本
                //     // 预计停喷时间:
                //     //     ${(data_dict.value["ratioWG"].slice(interval[0], interval[1])
                //     //         .reduce((accumulator: any, currentValue: any) => accumulator + currentValue, 0)
                //     //         / data_dict.value["ratioWG"].slice(interval[0], interval[1]).length) < 7 ? "大于60天" : "45天内"}
                //     style: {
                //         color: '#000', // 文本颜色
                //         fontWeight: 'bold' // 字体粗细
                //     },
                //     verticalAlign: 'top'
                // }
            });

        });
    });
};


const process_data = (data: any) => {
    const result = data.reduce((acc: any, item: any) => {
        Object.keys(item).forEach((key: any) => {
            if (!acc[key]) {
                acc[key] = [];
            }
            acc[key].push(item[key]);
        });

        return acc;
    }, {});
    return result;
};

const handleEvent = (e: any) => {
    // console.log(e)
    let xAxisValue = e.point.category; // 获取横坐标值
    // console.log("横坐标值：", xAxisValue);
    // 获取积液起止点
    if (!time_start_flag.value) {
        water_time_value1.value = xAxisValue;
    } else if (!time_end_flag.value) {
        water_time_value2.value = xAxisValue;
    }
};

const chartOptions1 = computed(() => ({
    chart: {
        type: 'spline',
    },
    rangeSelector: {
        enabled: false,
    },
    navigator: {
        enabled: false,
    },
    navigation: {
        mouseZoom: false
    },
    scrollbar: {
        enabled: false
    },

    legend: {
        enabled: true, // 启用图例
        align: 'top', // 图例对齐方式
        verticalAlign: 'left', // 图例垂直对齐方式
        // layout: 'vertical', // 图例布局方式
    },
    title: {
        // text: '数据趋势图'
    },
    series: [{
        name: '日产气',
        data: data_dict.value["gasPerDay"],
        yAxis: 0,
        tooltip: {
            valueSuffix: ' 万方'
        },
        events: {
            click: handleEvent
        },
        lineColor: '#FF9600' // 在这里设置线条颜色

    },
    {
        name: '日产水',
        data: data_dict.value["waterPerDay"],
        yAxis: 1,
        tooltip: {
            valueSuffix: ' 方'
        },
        events: {
            click: handleEvent
        },
        lineColor: '#0000FF' // 在这里设置线条颜色
    },

    ],

    yAxis: [
        {
            title: {
                text: '日产气(万方)'
            },
            // plotLines: [{
            //     value: 6,
            //     color: 'red',
            //     dashStyle: 'shortdash',
            //     width: 2,
            //     label: {
            //         text: '积液日产气阈值6(万方)'
            //     }
            // },],
            labels: {
                // format: '{value} %'
            },
        },
        {
            title: {
                text: '日产水(方)'
            },
            opposite: false,
            labels: {
                // format: '{value} %'
            },
        }
    ],
    xAxis: {
        // title: {
        //     text: '生产日期'
        // },
        categories: data_dict.value["date"],
        step: data_dict.value["date"].length / 20,
        // tickInterval: 100,
        labels: {
            // enabled: false,
        },
        events: {
            // 范围选择器改变的范围最终是改变坐标轴的范围，所以我们监听坐标的极值变更事件函数即可
            afterSetExtremes: function (e: any) {
                // e.min 和 e.max 为坐标轴当前的范围
                // console.log(e.min, e.max);
                chartRef2.value.chart.xAxis[0].setExtremes(e.min, e.max)
                chartRef3.value.chart.xAxis[0].setExtremes(e.min, e.max)
                chartRef4.value.chart.xAxis[0].setExtremes(e.min, e.max)
                // for (let key in secondDataDict.value) {
                //   if (Array.isArray(secondDataDict.value[key])) {
                //     secondDataDict.value[key] = newDataDict.value[key].slice(Math.round(e.min), Math.round(e.max));
                //   }
                // }
            }
        },
    },

    tooltip: {
        crosshairs: true,
        shared: true,
        refresh: function (e: any) {
            // console.log(`output->e`, e)
        },
    },
    marker: {
        symbol: 'square'
    },
}))
const chartOptions2 = computed(() => ({
    chart: {
        type: 'spline',
        // events: {
        //     click: function (e: any) {
        //         console.log(e)
        //     }
        // }
        zoomType: null,
        panning: false, //禁用放大
        pinchType: '', //禁用手势操作
    },
    rangeSelector: {
        enabled: false,
    },



    title: {
        text: ''
    },
    legend: {
        enabled: true, // 启用图例
        align: 'top', // 图例对齐方式
        verticalAlign: 'left', // 图例垂直对齐方式
        // layout: 'vertical', // 图例布局方式
    },
    series: [{
        name: '平均油压',
        data: data_dict.value["avgOilPressure"],
        lineColor: '#FF00FF',// 在这里设置线条颜色
        tooltip: {
            valueSuffix: 'MPa'
        },
        events: {
            click: handleEvent
        },
        showInNavigator: false,
    }, {
        name: '平均套压',
        data: data_dict.value["avgCasingPressure"],
        lineColor: '#002060',// 在这里设置线条颜色
        yAxis: 0,
        tooltip: {
            valueSuffix: ' MPa'
        },
        events: {
            click: handleEvent
        },
        showInNavigator: false,
    },

    {
        name: '生产时间',
        data: data_dict.value["time"],
        yAxis: 1,
        tooltip: {
            valueSuffix: ' 小时'
        },
        showInNavigator: true,

        events: {
            click: handleEvent
        }
    },
        // {
        //     name: 'label',
        //     data: data_dict.value["label"],
        //     lineColor: 'red',// 在这里设置线条颜色
        // },
    ],
    xAxis: {
        // title: {
        //     text: '生产日期'
        // },
        categories: data_dict.value["date"],
        step: data_dict.value["date"].length / 50,
        labels: {
            enabled: false
        },

        tickInterval: 100,
        events: {
            // 范围选择器改变的范围最终是改变坐标轴的范围，所以我们监听坐标的极值变更事件函数即可
            afterSetExtremes: function (e: any) {
                // e.min 和 e.max 为坐标轴当前的范围
                console.log(e.min, e.max);
                chartRef1.value.chart.xAxis[0].setExtremes(e.min, e.max)
                chartRef2.value.chart.xAxis[0].setExtremes(e.min, e.max)
                chartRef3.value.chart.xAxis[0].setExtremes(e.min, e.max)
                chartRef4.value.chart.xAxis[0].setExtremes(e.min, e.max)
                // for (let key in secondDataDict.value) {
                //   if (Array.isArray(secondDataDict.value[key])) {
                //     secondDataDict.value[key] = newDataDict.value[key].slice(Math.round(e.min), Math.round(e.max));
                //   }
                // }
            }
        },
    },
    yAxis: [{
        opposite: true,
        title: {
            text: '平均油套压'
        },
        // plotLines: [{
        //     value: 4,
        //     color: 'red',
        //     dashStyle: 'shortdash',
        //     width: 2,
        //     label: {
        //         text: '积液油压阈值4(MPa)'
        //     }
        // },],
        labels: {
            // format: '{value} %'
        },

    },
    {
        opposite: false,
        title: {
            text: '生产时间(h)'
        },

    },


    ],
    tooltip: {
        crosshairs: true,
        shared: true
    },
    marker: {
        symbol: 'square'
    },
}))
const chartOptions3 = computed(() => ({
    chart: {
        type: 'spline',
        marginBottom: 30
    },
    rangeSelector: {
        enabled: false,
    },
    navigator: {
        enabled: false,
    },
    scrollbar: {
        enabled: false
    },


    title: {
        text: ''
    },
    legend: {
        enabled: true, // 启用图例
        align: 'top', // 图例对齐方式
        verticalAlign: 'left', // 图例垂直对齐方式
        // layout: 'vertical', // 图例布局方式
    },
    series: [{
        name: '套油压差',
        data: data_dict.value["diffOC"],
        lineColor: '#10aec2',// 在这里设置线条颜色
        tooltip: {
            valueSuffix: 'MPa'
        },
        events: {
            click: handleEvent
        }
    },
    {
        name: '油压变化速率',
        data: data_dict.value["gasVaryRate"],
        yAxis: 1,
        lineColor: '#AFB42B',// 在这里设置线条颜色
        tooltip: {
            valueSuffix: 'MPa/天'
        },
        events: {
            click: handleEvent
        },

    },



    {
        name: 'label',
        data: data_dict.value["label"],
        marker: {
            symbol: 'triangle',
            fillColor: 'red'
        },
        events: {
            click: handleEvent
        },
        lineColor: 'red' // 在这里设置线条颜色
    },
    {
        name: 'pre_label',
        data: data_dict.value["pre_label"],
        marker: {
            symbol: 'triangle',
            fillColor: 'green'
        },
        events: {
            click: handleEvent
        },
        lineColor: 'green' // 在这里设置线条颜色
    },
    ],
    xAxis: {
        // title: {
        //     text: '生产日期'
        // },
        categories: data_dict.value["date"],
        step: data_dict.value["date"].length / 50,
        labels: {
            enabled: false
        },
        tickInterval: 100,
        events: {
            // 范围选择器改变的范围最终是改变坐标轴的范围，所以我们监听坐标的极值变更事件函数即可
            afterSetExtremes: function (e: any) {
                // e.min 和 e.max 为坐标轴当前的范围
                // console.log(e.min, e.max);
                chartRef1.value.chart.xAxis[0].setExtremes(e.min, e.max)
                chartRef2.value.chart.xAxis[0].setExtremes(e.min, e.max)
                chartRef3.value.chart.xAxis[0].setExtremes(e.min, e.max)
                chartRef4.value.chart.xAxis[0].setExtremes(e.min, e.max)
                // for (let key in secondDataDict.value) {
                //   if (Array.isArray(secondDataDict.value[key])) {
                //     secondDataDict.value[key] = newDataDict.value[key].slice(Math.round(e.min), Math.round(e.max));
                //   }
                // }
            }
        },

    },
    yAxis: [{
        opposite: true,
        title: {
            text: '套油压差'
        },
        labels: {
            // format: '{value} %'
        },
    },
    {
        opposite: false,
        title: {
            text: '油压变化速率'
        },
    },

    ],
    tooltip: {
        crosshairs: true,
        shared: true
    },
    marker: {
        symbol: 'square'
    },
}))
const chartOptions4 = computed(() => ({
    chart: {
        type: 'spline',
        marginBottom: 30
    },
    rangeSelector: {
        enabled: false,
    },
    navigator: {
        enabled: false,
    },
    scrollbar: {
        enabled: false
    },


    title: {
        text: ''
    },
    legend: {
        enabled: true, // 启用图例
        align: 'top', // 图例对齐方式
        verticalAlign: 'left', // 图例垂直对齐方式
        // layout: 'vertical', // 图例布局方式
    },
    series: [
        {
            name: '水气比',
            data: data_dict.value["ratioWG"],
            events: {
                click: handleEvent
            }

        },
        {
            name: '压差变化速率',
            data: data_dict.value["diffVaryRate"],
            yAxis: 1,
            lineColor: 'green',// 在这里设置线条颜色
            tooltip: {
                valueSuffix: 'MPa/天'
            },
            events: {
                click: handleEvent
            },
        },
        {
            name: '日产气变化速率',
            data: data_dict.value["gas_VaryRate"],
            yAxis: 0,
            tooltip: {
                valueSuffix: ''
            },
            events: {
                click: handleEvent
            },
            // lineColor: '#0000FF' // 在这里设置线条颜色
        },
        // {
        //     name: '可用时间段',
        //     data: data_dict.value["usefulLabel"],
        //     lineColor: 'blue',// 在这里设置线条颜色
        //     events: {
        //         click: handleEvent
        //     },
        // },
        {
            name: 'label',
            data: data_dict.value["label"],
            // yAxis: 1,
            marker: {
                symbol: 'triangle',
                fillColor: 'red'
            },
            lineColor: 'red' // 在这里设置线条颜色
        },
    ],
    xAxis: {
        // title: {
        //     text: '生产日期'
        // },
        lineColor: '#ffffff',//设置坐标颜色 
        categories: data_dict.value["date"],
        step: data_dict.value["date"].length / 50,
        labels: {
            enabled: false,
        },
        tickInterval: 100,
        events: {
            // 范围选择器改变的范围最终是改变坐标轴的范围，所以我们监听坐标的极值变更事件函数即可
            afterSetExtremes: function (e: any) {
                // e.min 和 e.max 为坐标轴当前的范围
                // console.log(e.min, e.max);
                chartRef1.value.chart.xAxis[0].setExtremes(e.min, e.max)
                chartRef2.value.chart.xAxis[0].setExtremes(e.min, e.max)
                chartRef3.value.chart.xAxis[0].setExtremes(e.min, e.max)
                chartRef4.value.chart.xAxis[0].setExtremes(e.min, e.max)
                // for (let key in secondDataDict.value) {
                //   if (Array.isArray(secondDataDict.value[key])) {
                //     secondDataDict.value[key] = newDataDict.value[key].slice(Math.round(e.min), Math.round(e.max));
                //   }
                // }
            }
        },
    },
    yAxis: [{
        opposite: true,
        title: {
            text: '日产气变化速率'
        },
    },
    {
        opposite: false,
        title: {
            text: '压差变化'
        },
    },

    ],
    tooltip: {
        crosshairs: true,
        shared: true
    },
    marker: {
        symbol: 'square'
    },
}))

const formatDate = (dateString: string | Date): string => {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}
const chageWellinfo = (time_value: any) => {
    // console.log(`output->`, time_value)
    const time_value_1 = time_value[0]
    const time_value_2 = time_value[1]
    const index_1 = newDataDict.value["date"].findIndex((item: string) => item == formatDate(time_value_1));
    const index_2 = newDataDict.value["date"].findIndex((item: string) => item == formatDate(time_value_2));

    let startIndex = 0;
    let endIndex = newDataDict.value["date"].length;

    if (index_1 !== -1) {
        startIndex = index_1;
    }
    if (index_2 !== -1) {
        endIndex = index_2 + 1;
    }

    for (let key in newDataDict.value) {
        // console.log(`output->key`, key)
        if (Array.isArray(newDataDict.value[key])) {
            data_dict.value[key] = newDataDict.value[key].slice(startIndex, endIndex);
        }
    }
}
const showPartDAta = (proportion: any) => {

    let startIndex = 0;
    let endIndex = Math.floor(newDataDict.value["date"].length * proportion);

    for (let key in newDataDict.value) {
        if (Array.isArray(newDataDict.value[key])) {
            data_dict.value[key] = newDataDict.value[key].slice(startIndex, endIndex);
        }
    }
    // console.log(`output->`, chartInstance)
}
const denose = async () => {
    // console.log(`output->water_time_value1`,water_time_value1)
    const params = ref({
        well_num: well_value.value.split('_')[0],
        cengwei_num: well_value.value.split('_')[1],
        start_time: water_time_value1.value,
    })
    reset()
    const { data } = await denoseData(params.value)
    ElMessageBox.alert(data.msg, {
        confirmButtonText: 'OK',
    })
    // reset()
    getWellInfo(well_value.value)

}
const time_start_ensure = () => {
    time_start_flag.value = true;
}
const time_end_ensure = () => {
    time_end_flag.value = true;
}
const reset = () => {
    time_start_flag.value = false;
    time_end_flag.value = false;
    water_time_value1.value = '';
    water_time_value2.value = '';

}
const saveAsWater = async () => {
    const params = ref({
        label: 1,
        well_num: well_value.value.split('_')[0],
        cengwei_num: well_value.value.split('_')[1],
        start_time: water_time_value1.value,
        end_time: water_time_value2
    })
    const { data } = await saveLabels(params.value)
    // console.log(`output->data`,data)
    ElMessageBox.alert(data.msg, {
        confirmButtonText: 'OK',
    })
    reset()
    getWellInfo(well_value.value)

}
const saveAsUsefulTimeInterval = async (_label: number) => {
    const params = ref({
        label: _label,
        well_num: well_value.value.split('_')[0],
        cengwei_num: well_value.value.split('_')[1],
        start_time: water_time_value1.value,
        end_time: water_time_value2.value
    })
    const { data } = await saveUsefulTimeInterval(params.value)
    ElMessageBox.alert(data.msg, {
        confirmButtonText: 'OK',
    })
    reset()
    getWellInfo(well_value.value)
}
const saveAsClean = async () => {
    const params = ref({
        label: 0,
        well_num: well_value.value.split('_')[0],
        cengwei_num: well_value.value.split('_')[1],
        start_time: water_time_value1.value,
        end_time: water_time_value2
    })
    const { data } = await saveLabels(params.value)
    if (data.code == "200") {
        ElMessageBox.alert("清除成功", {
            confirmButtonText: 'OK',
        })
    } else {
        ElMessageBox.alert("清除失败", {
            confirmButtonText: 'OK',
        })
    }
    reset()
    getWellInfo(well_value.value)

}



</script>

<style lang="scss" scoped>
.selector {
    display: flex;
    justify-content: space-between;
}

.selector_box {
    display: flex;
    justify-content: space-between;
}

.hc {
    margin-top: 10px;
    margin-right: 30px;
}

// .hc4 {
//     // margin-top: 20px;
//     margin-right: 30px;
//     // height: 200px;
// }

.charts {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    // height: 560px;
}

.select_title {
    display: flex;
    align-items: center;
    justify-content: center;
}

.affix_box {
    // background-color: var(--vt-c-white-soft);
    border-radius: 10px;

}
</style>